﻿Imports System.Web.Mvc
Imports Equipment.Business
Imports System.Web.Security

Public Class RequiresPageAccesAttribute : Inherits ActionFilterAttribute
    Private _page As Nullable(Of PageType)

    Public Property Page() As PageType
        Get
            Return Me._page
        End Get
        Set(ByVal value As PageType)
            Me._page = value
        End Set
    End Property

    Public Overrides Sub OnActionExecuting(ByVal filterContext As System.Web.Mvc.ActionExecutingContext)
        If Me._page.HasValue Then
            Dim currUser = Application.CurrentUserInfo
            If Not currUser.IsAuthenticated Then
                Dim redirectOnSuccess As String = filterContext.HttpContext.Request.Url.AbsolutePath
                Dim redirectUrl As String = String.Format("?ReturnUrl={0}", redirectOnSuccess)
                Dim loginUrl As String = FormsAuthentication.LoginUrl + redirectUrl
                If filterContext.HttpContext.User.Identity.IsAuthenticated Then
                    FormsAuthentication.SignOut()
                End If

                filterContext.HttpContext.Response.Redirect(loginUrl, True)
            Else
                Dim hasAccess As Boolean = currUser.HasPermissionFor(Me._page)
                If Not hasAccess Then
                    Throw New UnauthorizedAccessException("You don't have access to this page.")
                End If
            End If
        Else
            Throw New InvalidOperationException("No Page Specified")
        End If
    End Sub
End Class